package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.anno.RpcService;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author: jie.zhao
 * @create: 2021/05/18 23:06
 */
@Component
public class BeanFactoryPostDealProcessor implements BeanPostProcessor {

    @Autowired
    RpcClientProxy rpcClientProxy;

//
//    @Override
//    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//        System.out.println(beanName);
//        if(beanName.equals("iUserService")){
//            System.out.println("开始了");
//        }
//        return null;
//
//    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(beanName);
        if(beanName.equals("userController")){
            Field[] declaredFields = bean.getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
                for (int j = 0; j < declaredAnnotations.length; j++) {
                    if(declaredAnnotations[j].annotationType().equals(RpcService.class)){
                        field.setAccessible(true);
                        Object proxy = rpcClientProxy.createProxy(field.getType());
                        try {
                            field.set(bean,proxy);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        return null;
    }
}
